<template>
    <div>
        <van-popup class="popup-all" :show="showPopup" @update:show="updateShow" position="bottom"
            :style="{ height: '90%' }" round>
            <div class="popup-content">                
                <div style="background-color: #fff">
                    <CommonHeader type="黑" leftText="取消" title="注册" :onLeft="onClickLeft" />
                </div>
                <div style="margin: 12px; border-radius: 4px;">
                    <van-field class="field1" label="用户名" center v-model="username" placeholder="请输入用户名" />
                    <van-field class="field1" label="密码" center v-model="password"
                        :type="showPassword ? 'text' : 'password'" placeholder="请输入密码"
                        :right-icon="showPassword ? 'eye-o' : 'closed-eye'"
                        @click-right-icon="showPassword = !showPassword" />
                    <van-field class="field1" label="确认密码" center v-model="password2"
                        :type="showPassword2 ? 'text' : 'password'" placeholder="请输入确认密码"
                        :right-icon="showPassword2 ? 'eye-o' : 'closed-eye'"
                        @click-right-icon="showPassword2 = !showPassword2"/>
                    <van-field class="field1" label="手机号" v-model="userphone" center placeholder="请输入手机号" type="tel"
                        maxlength="11" />
                    <van-field class="field1" label="验证码" v-model="validCode" center placeholder="请输入验证码" type="number"
                        maxlength="4">
                        <template #button>
                            <van-button type="primary" round style="height: 25px; " :style="buttonStyle" :color="clocr"
                                :text="codebtn" @click="getVerificationCode" />
                        </template>
                    </van-field>
                </div>

                <div style="text-align: center; font-size: 13px; margin-top: 28px;">
                    <span style="color: #AAAAAA;">已有账号？</span>
                    <span @click="updateShow(false)" style="color: #16CE8A;">立即登录</span>
                </div>
                <div style="margin: 16px; margin-top: 32px;">
                    <van-button type="primary" round block @click="appRegister"
                        color="linear-gradient(to right, #00BF87, #25F0A0)">注册</van-button>
                </div>
                <div class="explain">
                    <p>
                        说明：
                    </p>
                    <p>
                        备  案  者：包括经营不分装备案、受委托代销备案、受委托生产备案、分支机构备案四种备案类型的用户。
                    </p>
                    <p>
                        密码说明：密码至少包含大、小写字母、数字、特殊字符中的三种，长度至少10位。
                    </p>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, computed, onBeforeUnmount } from 'vue';
import uiUtil from "@/util/UiUtil.js";
import { useRouter } from 'vue-router';

const router = useRouter();
const emit = defineEmits(['update:show']);
const props = defineProps({
    show: {
        default: false
    },
});
watch(() => props.show, (newValue, oldValue) => {
    showPopup.value = newValue
})
const showPopup = ref(props.show);
const updateShow = (value) => {
    emit('update:show', value);
};

const username = ref('');
const password = ref('');
const password2 = ref('');
const userphone = ref('');
const validCode = ref('');
const showPassword = ref(false);
const showPassword2 = ref(false);

const clocr = ref('linear-gradient(to right, #00BF87, #25F0A0)');
const codebtn = ref('获取验证码');

const textColor = ref('white');

const buttonStyle = computed(() => {
    return {
        color: textColor.value
    };
});

const getVerificationCode = (event) => {
    if (isCounting.value) return; // 防止重复获取验证码
    if (userphone === null || userphone.value === null || userphone.value === '' || userphone.value.length < 11) {
        uiUtil.toast("请输入正确的手机号");
        return
    }
    console.log('获取验证码', userphone.value);
    //http://114.242.25.97:20167/api/seedarchive/sms/sendValidCode
    // 获取验证码操作
    const data = {
        appName: '',
        companyName: '',
        effectiveTime: '3',
        method: '',
        password: '',
        phones: userphone.value,
        templateNo: '',
        username: '',
        verificationCode: '',
        needCheckPhone: false,
    }
    uiUtil.http().postObj({
        url: uiUtil.urlPath.sendValidCode,
        data: data,
        start: () => {
            uiUtil.toastLoading('加载中...');
        },
        succeed: (res) => {
            if (!res) {
                uiUtil.toastFail('网络超时');
                return
            }
            if (!res || !res.code || 200 != res.code) {
                uiUtil.toastFail(res.msg);
                return
            }
            startCountdown()
            uiUtil.toastSuccess(res.data.validcode);
        },
        failed: (err) => {
            uiUtil.toastFail('注册失败：' + err);
        },
        finish: (type) => {
            console.log('finish=', type)
            // uiUtil.toastClose();
        }
    })
};

const appRegister = () => {
    if (username === null || username.value === null || username.value === '') {
        uiUtil.toast("请输入用户名");
        return
    }
    if (password === null || password.value === null || password.value === '') {
        uiUtil.toast("请输入密码");
        return
    }
    
    if (password2 === null || password2.value === null || password2.value === '') {
        uiUtil.toast("请输入确认密码");
        return
    }
    if(password.value != password2.value){
        uiUtil.toast("两次密码输入不一致");
        return
    }
    if (!uiUtil.containsThreeCategories(password.value)) {
        uiUtil.toast("密码至少包含大、小写字母、数字、特殊字符中的三种。");
        return
    }
    if (password.value.length < 10) {
        uiUtil.toast("密码长度至少10位。");
        return
    }
    if (userphone === null || userphone.value === null || userphone.value === '' || userphone.value.length < 11) {
        uiUtil.toast("请输入正确的手机号");
        return
    }
    if (validCode === null || validCode.value === null || validCode.value === '') {
        uiUtil.toast("请输入验证码");
        return
    }
    countdown.value = 0
    let data = {
        userLoginName: username.value,
        linkmanPhone: userphone.value,
        enterpriseType: '备案者',
        validCode: validCode.value,
        userPassword: uiUtil.encrypt(password.value),
        entepriseName: '',
        enterpriseCode: '',
    }
    uiUtil.http().postObj({
        url: uiUtil.urlPath.appRegister,
        data: data,
        start: () => {
            uiUtil.toastLoading('加载中...');
        },
        succeed: (res) => {
            if (!res) {
                uiUtil.toastFail('网络超时');
                return
            }
            if (!res || !res.code || 200 != res.code) {
                uiUtil.toastFail(res.msg);
                return
            }
            localStorage.setItem(uiUtil.urlPath.keys.token, res.data.Tokens);
            localStorage.setItem(uiUtil.urlPath.keys.user, JSON.stringify(res.data));
            var un = res.data.UserLoginName
            console.log('uname1======', un)
            localStorage.setItem(uiUtil.urlPath.keys.username, un);
            localStorage.setItem(uiUtil.urlPath.keys.uid, res.data.UserID);
            const token = localStorage.getItem('token')
            const uname = localStorage.getItem(uiUtil.urlPath.keys.username)
            const uid = localStorage.getItem('uid')

            console.log('Authorization-l======', token)
            console.log('uname======', uname, res.data.UserLoginName, localStorage.getItem(uiUtil.urlPath.keys.username))
            console.log('uid======', uid)
            uiUtil.toastClose();
            router.push({ path: uiUtil.routerPath.main });
        },
        failed: (err) => {
            // debugger;
            uiUtil.toastFail('登录失败：' + err);
        },
        finish: (type) => {
            // debugger;
            console.log('finish=', type)
            // uiUtil.toastClose();
        }
    })
};


//倒计时
const countdown = ref(60); // 初始化倒计时为60秒
const isCounting = ref(false); // 是否正在倒计时
let intervalId; // 保存setInterval的ID

const startCountdown = () => {
    if (isCounting.value) return; // 防止重复启动倒计时
    isCounting.value = true;
    countdown.value = 60; // 每次点击按钮时重置倒计时为60秒
    intervalId = window.setInterval(() => {
        if (countdown.value > 1) {
            countdown.value -= 1;
            console.log(countdown.value)
            clocr.value = ('linear-gradient(to right, #F5F5F5, #F5F5F5)');
            textColor.value = ('#AAAAAA')
            codebtn.value = countdown.value + 's后重新发送'
        } else {
            clocr.value = ('linear-gradient(to right, #00BF87, #25F0A0)');
            textColor.value = ('#ffffff')
            codebtn.value = '获取验证码'
            clearInterval(intervalId);
            isCounting.value = false;
        }
    }, 1000); // 每秒钟更新一次倒计时
};
// 清理计时器，当组件卸载时防止内存泄漏 
onBeforeUnmount(() => {
    if (intervalId !== undefined) {
        clearInterval(intervalId);
    }
});
//倒计时结束

const onClickLeft = () => {
    updateShow(false)
};
</script>

<style scoped>
.popup-content {
    background-color: #F3F9F8;
    height: 100%;
}

.rounded-field {
    border-radius: 32px;
    padding: 8px 16px;
}


.left-text {
    color: black;
    cursor: pointer;
}

.popup-content :deep(.van-search__content) {
    padding: 0 16px;
    background-color: #F1F1F1;
}
.explain{
    margin: 0 20px;
    font-size: 10px;
    color: #AAAAAA;
    font-weight: 400;
} 
.explain p{
    font-size: 10px;
    color: #AAAAAA;
    font-weight: 400;
} 
</style>